package com.example.wzq.englishpage;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.PagerAdapter;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * 创建时间：2017/6/21
 * 作者：kb_jay
 * 功能描述：自定义viewGroup，实现拖拽显示底部view的效果
 */

public class CustomEP extends ViewGroup {

    private static final float DEFAULT_MAX_HEIGHT = 0.5F;
    private static final int DEFAULT_TITLE_HEIGHT = 50;

    private float mBottomMaxHeight;
    private View mContentView;
    private View mAnswerView;
    private int mWindowHeight;
    private int mWindowWidth;
    private int measuredHeight;
    private int measuredWidth;
    private ViewDragHelper mViewDragHelper;
    private int mTitleHeight;
    private int mAnswerHeight;
    private CustomVP mVp;
    private int mAnswerVisableHeight;


    public CustomEP(Context context) {
        this(context, null);
    }

    public CustomEP(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomEP(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomEP);
        mBottomMaxHeight = typedArray.getFloat(R.styleable.CustomEP_bottomMaxHeight, DEFAULT_MAX_HEIGHT);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mWindowHeight = wm.getDefaultDisplay().getHeight();
        mWindowWidth = wm.getDefaultDisplay().getWidth();
        Log.d("kbjay", mWindowHeight + "----window height");

        mViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {

            @Override
            public boolean tryCaptureView(View child, int pointerId) {
                if (child == mAnswerView) {
                    return true;
                }
                return false;
            }

            @Override
            public int clampViewPositionHorizontal(View child, int left, int dx) {
                return super.clampViewPositionHorizontal(child, left, dx);
            }

            @Override
            public int clampViewPositionVertical(View child, int top, int dy) {

                if (top > measuredHeight - mTitleHeight) {
                    mAnswerVisableHeight = measuredHeight - mTitleHeight;
                    return (int) (measuredHeight - mTitleHeight);
                } else if (top < measuredHeight - mAnswerHeight) {
                    mAnswerVisableHeight = mAnswerHeight;
                    return measuredHeight - mAnswerHeight;
                } else {
                    mAnswerVisableHeight = measuredHeight - top;
                    //   Log.d("kbjay", (measuredHeight - top) + "========================");
                    return top;
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return mViewDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mViewDragHelper.processTouchEvent(event);
        return true;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
        int maxHeight = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(
                resolveSizeAndState(maxWidth, widthMeasureSpec, 0),
                resolveSizeAndState(maxHeight, heightMeasureSpec, 0));

        measuredHeight = getMeasuredHeight();
        measuredWidth = getMeasuredWidth();

        Log.d("kbjay", measuredHeight + "-onMeasure-" + measuredWidth);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mTitleHeight = dip2px(DEFAULT_TITLE_HEIGHT);
        mAnswerVisableHeight = mTitleHeight;
        mAnswerHeight = mAnswerView.getMeasuredHeight();
        Log.d("kbjay", mTitleHeight + "-title and answer height--" + mAnswerHeight);
    }

    private int dip2px(int dp) {
        float density = this.getContext().getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d("kbjay", "onlayout");
        //摆放两个view
        if (mContentView != null) {
            mContentView.layout(0, 0, measuredWidth, measuredHeight);
        }

        if (mAnswerView != null) {
            mAnswerView.layout(0, (int) (measuredHeight - mAnswerVisableHeight), measuredWidth, (int) (measuredHeight - mAnswerVisableHeight + mAnswerHeight));
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        Log.d("kbjay", "onfinishInflate");
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView != null) {
                if (childView.getId() == R.id.ep_content) {
                    mContentView = childView;
                    initContent();
                } else if (childView.getId() == R.id.ep_answer) {
                    mAnswerView = childView;
                    initAnswer();
                }
            }

        }
    }

    //初始化答案页
    private void initAnswer() {
        //gei title she zhi shoushi jianting
        TextView mTvTitle = (TextView) mAnswerView.findViewById(R.id.ep_tv_title);

/*

        final GestureDetector gestureDetector = new GestureDetector(getContext(), new MyGestureListener());
        mTvTitle.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                 gestureDetector.onTouchEvent(event);
                return true;
            }
        });

*/
        //通过ViewDragHelper给答题页添加拖拽效果
        mVp = (CustomVP) mAnswerView.findViewById(R.id.ep_vp);
        final ArrayList<TextView> datas = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            TextView textView = new TextView(getContext());
            textView.setText(i + "");
            textView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER);
            datas.add(textView);
        }
        mVp.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return datas.size();
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(datas.get(position));
                return datas.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
        });


    }

    //初始化内容页
    private void initContent() {

    }


    class MyGestureListener implements GestureDetector.OnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            Toast.makeText(getContext(), "onDown", Toast.LENGTH_SHORT).show();
            Log.d("kbjay", "onDown");
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            Toast.makeText(getContext(), "onShowPress", Toast.LENGTH_SHORT).show();
            Log.d("kbjay", "onShowPress");
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            Toast.makeText(getContext(), "onSingleTapUp", Toast.LENGTH_LONG).show();
            Log.d("kbjay", "onSingleTapUp");

            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            Toast.makeText(getContext(), "onScroll", Toast.LENGTH_LONG).show();
            Log.d("kbjay", "onScroll");
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            Log.d("kbjay", "onLongPress");
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.d("kbjay", "onFling");
            return false;
        }
    }
}
